package com.sunlg.smarthome.data.remote;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.C;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by sunlg on 2016/12/2.
 */
public class OKHttpUtil {

    private SHService service;
    private Context mContext = App.getInstance().getApplicationContext();

    public SHService getService() {

        OkHttpClient client = new OkHttpClient.Builder()
                .cookieJar(new CookiesManager())
                .connectTimeout(C.Net.CONNECT_TIME_OUT, TimeUnit.SECONDS)
                .writeTimeout(C.Net.WRITE_TIME_OUT, TimeUnit.SECONDS)
                .readTimeout(C.Net.READ_TIME_OUT, TimeUnit.SECONDS)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(C.API.SMARTHOME_API)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .client(client)
                .build();
        service = retrofit.create(SHService.class);
        return service;
    }

    /**
     * 判断网络是否可用
     *
     * @param context Context对象
     */
    public  Boolean isNetworkReachable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo current = cm.getActiveNetworkInfo();
        if (current == null) {
            return false;
        }
        return (current.isAvailable());
    }

    /**
     * 自动管理Cookies
     */
    private static class CookiesManager implements CookieJar {
        private final PersistentCookieStore cookieStore =
                new PersistentCookieStore(App.getInstance().getApplicationContext());

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            if (cookies != null && cookies.size() > 0) {
                for (Cookie item : cookies) {
                    cookieStore.add(url, item);
                }
            }
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            List<Cookie> cookies = cookieStore.get(url);
            System.out.println(cookies.toString());
            return cookies;
        }
    }
}
